package ar.com.pragmatia.lanacion.data;

import java.lang.reflect.Field;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import ar.com.pragmatia.lanacion.app.App;
import ar.com.pragmatia.lanacion.utils.Strings;

public class DataHelper {

	private static final String DATABASE_NAME = "la_nacion.sqlite3";
	private static final String DATA_CLASSES_PACKAGE = "ar.com.pragmatia.lanacion.data";

	private static final int DATABASE_VERSION = 48;

	
	private static final String[] TABLE_NAMES = { Client.TABLE_NAME,
			Visit.TABLE_NAME, VisitClaim.TABLE_NAME,
			VisitDeliveredItem.TABLE_NAME, VisitReason.TABLE_NAME,
			VisitResult.TABLE_NAME, RoadMapFilter.TABLE_NAME,
			TravelingLoad.TABLE_NAME, User.TABLE_NAME,
			PendingClient.TABLE_NAME, Article.TABLE_NAME, Order.TABLE_NAME,
			OrderDetail.TABLE_NAME };

	private SQLiteDatabase db;

	public DataHelper(Context context) {
		DbHelper openHelper = new DbHelper(context);
		this.db = openHelper.getWritableDatabase();
	}

	public SQLiteDatabase getDb() {
		return this.db;
	}

	private static class DbHelper extends SQLiteOpenHelper {

		DbHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			// Do the "CREATE TABLE ..." for every table needed by the app
			for (int i = 0; i < TABLE_NAMES.length; i++) {

				String[] fields = null;
				String[] fieldsCopy = null;
				try {

					String className = Strings.camelize(Strings
							.singularize(TABLE_NAMES[i]));
					Class<?> clazz = Class.forName(DATA_CLASSES_PACKAGE + "."
							+ className);
					Field fieldsField = clazz.getField("FIELDS");
					fields = (String[]) fieldsField.get(clazz);

					fieldsCopy = fields.clone();

					Field autoIncrementField = clazz.getField("ID");
					String autoIncrement = (String) autoIncrementField
							.get(clazz);

					for (int j = 0; j < fields.length; j++) {
						if (fieldsCopy[j] == "id") {
							fieldsCopy[j] += " "
									+ ("INTEGER PRIMARY KEY" + " " + autoIncrement)
											.trim();
						} else {
							fieldsCopy[j] += " TEXT";
						}
					}

				} catch (ClassNotFoundException e) {
					App.log("DataHelper", "onCreate", e.getMessage());
				} catch (SecurityException e) {
					App.log("DataHelper", "onCreate", e.getMessage());
				} catch (NoSuchFieldException e) {
					App.log("DataHelper", "onCreate", e.getMessage());
				} catch (IllegalArgumentException e) {
					App.log("DataHelper", "onCreate", e.getMessage());
				} catch (IllegalAccessException e) {
					App.log("DataHelper", "onCreate", e.getMessage());
				}

				String sql = "CREATE TABLE " + TABLE_NAMES[i] + " ("
						+ Strings.join(fieldsCopy, ",") + ")";
				db.execSQL(sql);
			}

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w("Example",
					"Upgrading database, this will drop tables and recreate.");

			for (int i = 0; i < TABLE_NAMES.length; i++) {
				db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAMES[i]);
			}

			this.onCreate(db);
		}
	}

}